package com.wutianyi.servlet.upload;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.wutianyi.constants.Constants;
import com.wutianyi.entity.EntityTypeEnum;

public class UploadServlet extends HttpServlet
{

    /**
     * 
     */
    private static final long serialVersionUID = 183074482401681824L;

    private final String P_FILE_NAME = "filename";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        sfu.setHeaderEncoding("utf-8");
        try
        {
            @SuppressWarnings("unchecked")
            List<FileItem> fileItems = sfu.parseRequest(req);
            String fileName = null;
            byte[] buf = null;
            for (FileItem fi : fileItems)
            {
                if (fi.isFormField())
                {
                    if (fi.getFieldName().equals(P_FILE_NAME))
                    {
                        fileName = fi.getString();
                    }
                }
                else
                {
                    buf = fi.get();
                }
            }
            PrintWriter pw = resp.getWriter();
            if (StringUtils.isBlank(fileName) || null == buf || 0 == buf.length)
            {
                pw.print("无效参数");
                return;
            }
            Entity entity = new Entity(EntityTypeEnum.Files.name(), fileName);
            entity.setProperty(Constants.FILE_VALUE, new Blob(buf));
            DatastoreServiceFactory.getDatastoreService().put(entity);
            pw.print("1");
        }
        catch (FileUploadException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
